package logic

import (
	"ViewSrv/global/model"
	"context"
	"encoding/json"
	"fmt"
	"github.com/redis/go-redis/v9"
	"time"

	"ViewSrv/internal/svc"
	"ViewSrv/view"

	"github.com/zeromicro/go-zero/core/logx"
)

type VideoListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewVideoListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *VideoListLogic {
	return &VideoListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *VideoListLogic) VideoList(in *view.VideoListRequest) (*view.VideoListResponse, error) {
	// todo: add your logic here and delete this line
	var video []model.Video
	var key = fmt.Sprintf("view_log:%s,%s,%d,%d,%d,%d", in.Word, in.Address, in.Len, in.IsVip, in.TypeId, in.Year)
	var Datas []*view.FormView
	data := model.RDB.Get(model.Ctx, key).Val()
	if data == "" {
		sql := model.DB.Debug().Model(&model.Video{})
		if in.Address != "" {
			sql.Where("address = ?", in.Address)
		}
		if in.TypeId != 0 {
			sql.Where("type_id = ?", in.TypeId)
		}
		if in.Year != 0 {
			lift := time.Date(int(in.Year), 0, 1, 0, 0, 0, 0, time.Local)
			right := lift.AddDate(1, 0, 0)
			fmt.Println(lift, right)
			sql.Where("created_at >= ? && created_at<= ?", lift, right)
		}
		if in.Word != "" {
			sql.Where("title like ?", "%"+in.Word+"%")
		}
		if in.Len != 0 {
			sql.Where("len > ?", in.Len)
		}
		if in.IsVip != 0 {
			sql.Where("is_vip = ?", in.IsVip)
		}
		if err := sql.Find(&video).Error; err != nil {
			return nil, err
		}

		num := model.RDB.ZScore(model.Ctx, "hot", in.Word).Val()
		if num == 0 {
			model.RDB.ZAdd(model.Ctx, "hot", redis.Z{1, in.Word})
		} else {
			model.RDB.ZAdd(model.Ctx, "hot", redis.Z{num + 1, in.Word})
		}
		model.RDB.LPush(model.Ctx, "log", in.Word)
		lens := model.RDB.LLen(model.Ctx, "log").Val()
		if lens > 3 {
			model.RDB.RPop(model.Ctx, "log")
		}

		for _, v := range video {
			var data = &view.FormView{
				Id:    int64(v.ID),
				Title: v.Title,
			}
			Datas = append(Datas, data)
		}
		set, _ := json.Marshal(Datas)
		model.RDB.Set(model.Ctx, key, string(set), time.Second*180)
	} else {
		json.Unmarshal([]byte(data), &Datas)
	}
	return &view.VideoListResponse{
		Videos: Datas,
	}, nil
}
